package com.huabo.cybermonitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.HttpClient;
import com.hbfk.util.JsonBean;
import com.hbfk.util.PageInfo;
import com.huabo.cybermonitor.entity.*;
import com.huabo.cybermonitor.service.IFormControlruleService;
import com.huabo.cybermonitor.service.IOrganizationService;
import com.huabo.cybermonitor.util.ConstClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@Slf4j
@Api(value = "表单监控-业务表单监控", tags = {"表单监控-业务表单监控所有接口"})
@RequestMapping(value = "/cyber/ywbdjkController")
@SuppressWarnings("all")
public class YwbdjkController {

    private static final String formurl = "http://59.110.222.142:8001";

    @Autowired
    private IFormControlruleService iFormControlruleService;

    @Autowired
    IOrganizationService iorganizationService;

    /**
     * 组织列表
     */
    @GetMapping("/rulecontrol/org_list")
    @ApiOperation("组织列表")
    public JsonBean rulecontrol_org_list(@ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) throws Exception {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        // 在token 取到当前用户
        TblStaffUtil staff = DealUserToken.parseUserToken(token);//staff

        Map map = new HashMap(1);
        map.put("orgid", iorganizationService.getById(staff.getCurrentOrg().getOrgid()));
        return new JsonBean(200, "成功", map);
    }


    /**
     * 规则列表
     */
    @GetMapping("/rulecontrol/rule_list")
    @ApiOperation("规则列表")
    public JsonBean rule_list(@ApiParam(name = "orgId", value = "传deptid条件deptid,不传按orgid查询-116821") @RequestParam(value = "orgId", required = false) String orgId,
                              @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
                              @ApiParam(name = "pageSize", value = "pageSize") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                              @ApiParam(name = "ruleno", value = "nc/01") @RequestParam(value = "ruleno", required = false) String ruleno,
                              @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) throws Exception {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        // 在token 取到当前用户
        TblStaffUtil staff = DealUserToken.parseUserToken(token);//staff
        FormControlrule tfcr=new FormControlrule();
        tfcr.setRuleno(ruleno);

        Map map = new HashMap();
        try {
            if (pageNumber == null) {
                pageNumber = 1;
            }

            if (orgId==null) {
                orgId = staff.getCurrentOrg().getOrgid().toString();
                tfcr.setOrgid(new BigDecimal(orgId));
            } else {
                tfcr.setDeptid(new BigDecimal(orgId));
            }
            IPage<FormControlrule> iPage = new Page<>(pageNumber, pageSize);
            QueryWrapper<FormControlrule> queryWrapper = new QueryWrapper<>();

            if (tfcr.getOrgid() != null) {
                queryWrapper.eq("ORGID", tfcr.getOrgid());
            }
            if (tfcr.getDeptid() != null) {
                queryWrapper.eq("DEPTID", tfcr.getDeptid());
            }
            if (tfcr.getRuleno() != null) {
                queryWrapper.like("RULENO",  tfcr.getRuleno());
            }
            queryWrapper.orderByDesc("createtime");
            map.put("orgId", orgId);
            map.put("pageInfo", iFormControlruleService.page(iPage, queryWrapper));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", map);
    }


    /**
     * 规则转到添加页面
     */
    @GetMapping("/rulecontrol/rule_gotoAddPage")
    @ApiOperation("规则转到添加页面")
    public JsonBean rule_gotoAddPages(@ApiParam(name = "orgId", value = "组织机构编码") @RequestParam(value = "orgId", required = true) String orgId,
                                      @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        Map map = new HashMap();
        try {
            Organization org = this.iorganizationService.getById(orgId);
            map.put("org", org);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", map);
    }


    /**
     * 保存规则
     *
     * @param attribute
     * @param longUser
     * @param rule
     * @param replacekey
     * @param replacekvalue
     * @param replacetype
     * @param reorg
     * @param orgid
     * @param eleId
     * @param fieldId
     * @return
     */
    @PostMapping("/rulecontrol/save_fromRule")
    @ApiOperation("保存规则")
    public JsonBean save_fromRule(
            @ApiParam(name = "rule", value = "rule")  FormControlruleDto rule,
            @ApiParam(name = "replacekey", value = "replacekey") @RequestParam(value = "replacekey", required = false) String[] replacekey,
            @ApiParam(name = "replacekvalue", value = "replacekvalue") @RequestParam(value = "replacekvalue", required = false) String[] replacekvalue,
            @ApiParam(name = "replacetype", value = "replacetype") @RequestParam(value = "replacetype", required = false) String[] replacetype,
            @ApiParam(name = "reorg", value = "orgid以逗号隔开形式 198333,198328") @RequestParam(value = "reorg", required = false) String reorg,
            @ApiParam(name = "orgid", value = "所属部门id") @RequestParam(value = "orgid", required = false) String orgid,
            @ApiParam(name = "eleId", value = "eleId") @RequestParam(value = "eleId", required = false) BigDecimal eleId,
            @ApiParam(name = "fieldId", value = "fieldId") @RequestParam(value = "fieldId", required = false) String fieldId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token)throws Exception {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        // 在token 取到当前用户
        TblStaffUtil staff = DealUserToken.parseUserToken(token);//staff

        FormControlrule fc=new FormControlrule();


        fc.setCreatestaff(staff.getStaffid());
        fc.setCreatetime(LocalDateTime.now());
        fc.setDeptid(new BigDecimal(orgid));
        fc.setOrgid(staff.getCurrentOrg().getOrgid());
        fc.setReturnresult(rule.getReturnresult());
        fc.setRuleno(rule.getRuleno());
        fc.setRulememo(rule.getRulememo());
        fc.setRulesql(rule.getRulesql());
        fc.setRuletip(rule.getRuletip());
        fc.setRulestatus(rule.getRulestatus());
        fc.setRulename(rule.getRulename());

        if(fieldId != null){
            fc.setFieldid(new BigDecimal(fieldId));
        }
        HashMap<String, Object> resultMap = new HashMap<String, Object>(0);
        try {
            String rulesql = rule.getRulesql().toUpperCase();
            if (rulesql.indexOf("FROM") == -1 || rulesql.indexOf("SELECT") == -1 || rulesql.indexOf("CREATE") != -1 || rulesql.indexOf("DROP") != -1 || rulesql.indexOf("UPDATE") != -1 || rulesql.indexOf("DELETE") != -1 || rulesql.indexOf("GRANT") != -1) {
                resultMap.put("result", "规则对应SQL语句不规范！");
                return new JsonBean(200, "错误", resultMap);
            }
            String result = iFormControlruleService.insertFormControlRule(fc, replacekey, replacekvalue, replacetype, eleId, reorg);
            resultMap.put("result", 0);
            resultMap.put("ruleId", result);
            return new JsonBean(200, "成功", resultMap);

        } catch (Exception e) {
            resultMap.put("result", "规则对应SQL语句执行失败！");
            return new JsonBean(500, "规则对应SQL语句执行失败！", resultMap);
        }

    }


    /**
     * 规则转到修改页面
     */
    @GetMapping("/rulecontrol/rule_gotoModifyPage")
    @ApiOperation("规则转到修改页面")
    public JsonBean rule_gotoModifyPage(@ApiParam(name = "ruleid", value = "ruleid") @RequestParam(value = "ruleid", required = true) String ruleid,
                                        @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        Map map = new HashMap();
        try {
            FormControlrule rule = this.iFormControlruleService.getById(ruleid);
            HashMap<String, Object> fields = new HashMap<String, Object>(0);
            fields.put("ruleid", ruleid);
            String result = HttpClient.request(formurl + "/form/findFormEleNameByRuleId", fields, null);
            if (result != null && !"".equals(result)) {
                String[] eles = result.split(",");
                map.put("eleId", eles[0]);
                map.put("eleName", eles[1]);
            }
            map.put("rule", rule);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", map);
    }


    /**
     * 自定义表单 表单列表页面  查询所有在业务流程中的表单
     */
    @GetMapping(value = "/rulecontrol/findFormInfoListInFlow")
    @ApiOperation("自定义表单 表单列表页面  查询所有在业务流程中的表单")
    public JsonBean findFormInfoListInFlow(@ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token,
                                           @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
                                           @ApiParam(name = "pageSize", value = "pageSize") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                           @ApiParam(name = "FORMNO", value = "FORMNO") @RequestParam(value = "FORMNO", required = false) String formNo,
                                           @ApiParam(name = "FORMNAME", value = "FORMNAME") @RequestParam(value = "FORMNAME", required = false) String formName,
                                           @ApiParam(name = "FORMNOSTATUS", value = "FORMNOSTATUS") @RequestParam(value = "FORMNOSTATUS", required = false) String formNoStatus,
                                           @ApiParam(name = "FORMNAMESTATUS", value = "FORMNAMESTATUS") @RequestParam(value = "FORMNAMESTATUS", required = false) String formNameStatus,
                                           @ApiParam(name = "idname", value = "idname") @RequestParam("idname") String idname,
                                           @ApiParam(name = "textname", value = "textname") @RequestParam("textname") String textname) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        Map map = new HashMap();
        try {
            if (pageNumber == null) {
                pageNumber = 1;
            }
            if (pageSize == null) {
                pageSize = 15;
            }
            // 在token 取到当前用户
            TblStaffUtil staff = DealUserToken.parseUserToken(token);//staff
            HashMap<String, Object> fields = new HashMap<String, Object>(0);
            fields.put("orgId", staff.getCurrentOrg().getOrgid());
            fields.put("pageNumber", pageNumber);
            fields.put("pageSize", pageSize);
            fields.put("formNo", formNo);
            fields.put("formName", formName);
            fields.put("formNoStatus", formNoStatus);
            fields.put("formNameStatus", formNameStatus);
            String result = HttpClient.request(formurl + "/form/selectFormInfoListInTblFlow", fields, null);
            JSONObject resultjs = JSONObject.parseObject(result);
            PageInfo<FormInfo> pageInfo = new PageInfo<FormInfo>();
            if ("true".equals(resultjs.get("result").toString())) {
                pageInfo.setTotalRecord(Integer.parseInt(resultjs.get("count").toString()));
                String list = resultjs.get("list").toString();
                List<FormInfo> formList = JSONObject.parseArray(list, FormInfo.class);
                pageInfo.setTlist(formList);
            } else {
                List<FormInfo> list = new ArrayList<FormInfo>(0);
                pageInfo.setTotalRecord(0);
                pageInfo.setTlist(list);
            }
            pageInfo.setCurrentPage(pageNumber);
            pageInfo.setPageSize(pageSize);
            map.put("pageInfo", pageInfo);
            map.put("idname", idname);
            map.put("textname", textname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", map);
    }


    /**
     * 自定义表单 表单列表页面
     */
    @GetMapping("/rulecontrol/findFormReportListInfo")
    @ApiOperation("自定义表单 表单列表页面")
    public JsonBean form_findFormReportListInfo(@ApiParam(name = "formId", value = "表单id") @RequestParam(value = "formId", required = true) Integer formId,
                                                @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        Map<String, Object> map = new HashMap<String, Object>(0);
        try {
            HashMap<String, Object> fields = new HashMap<String, Object>(0);
            fields.put("formId", formId);
            String result = HttpClient.request(formurl + "/form/findFormReportListInfo", fields, null);
            JSONObject resultjs = JSONObject.parseObject(result);
            if ("true".equals(resultjs.get("result").toString())) {
                String list = resultjs.get("eleList").toString();
                List<FormElements> eleList = JSONObject.parseArray(list, FormElements.class);
                map.put("result", 0);
                map.put("eleList", eleList);
            } else {
                map.put("result", 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", map);
    }

    /**
     * 修改表单规则
     */
    @GetMapping("/rulecontrol/modify_fromRule")
    @ApiOperation("修改表单规则")
    public JsonBean modify_fromRule(@ApiParam(name = "rule", value = "rule")  FormControlruleDto rule,
                                    @ApiParam(name = "reorg", value = "orgid以逗号隔开形式 198333,198328") @RequestParam(value = "reorg", required = false) String reorg,
                                    @ApiParam(name = "replacekey", value = "replacekey") @RequestParam(value = "replacekey", required = false) String[] replacekey,
                                    @ApiParam(name = "replacekvalue", value = "replacekvalue") @RequestParam(value = "replacekvalue", required = false) String[] replacekvalue,
                                    @ApiParam(name = "replacetype", value = "replacetype") @RequestParam(value = "replacetype", required = false) String[] replacetype,
                                    @ApiParam(name = "reid", value = "reid") @RequestParam(value = "reid", required = false) String[] reid,
                                    @ApiParam(name = "eleId", value = "eleId") @RequestParam(value = "eleId", required = false) BigDecimal eleId,
                                    @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        HashMap<String, Object> resultMap = new HashMap<String, Object>(0);
        try {
            String rulesql = rule.getRulesql().toUpperCase();
            if (rulesql.indexOf("FROM") == -1 || rulesql.indexOf("SELECT") == -1 || rulesql.indexOf("CREATE") != -1 || rulesql.indexOf("DROP") != -1 || rulesql.indexOf("UPDATE") != -1 || rulesql.indexOf("DELETE") != -1 || rulesql.indexOf("GRANT") != -1) {
                resultMap.put("result", "规则对应SQL语句不规范！");
                return new JsonBean(200, "失败", resultMap);
            }
            String result = iFormControlruleService.modifyFormControlRule(rule, replacekey, replacekvalue, replacetype, eleId, reid, reorg);
            resultMap.put("result", 0);
            resultMap.put("ruleid", result);
        } catch (Exception e) {
            resultMap.put("result", "规则对应SQL语句执行失败！");
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", resultMap);
    }


    /**
     * 修改表单规则状态
     */
    @GetMapping("/rulecontrol/modify_ruleStatus")
    @ApiOperation("修改表单规则状态")
    public JsonBean modify_ruleStatus(@ApiParam(name = "ruleid", value = "ruleid") @RequestParam(value = "ruleid", required = true) String ruleid,
                                      @ApiParam(name = "status", value = "status") @RequestParam(value = "status", required = true) String status,
                                      @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        try {
            this.iFormControlruleService.modifyFormStatus(ruleid, status);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "修改成功", "0");
    }


    /**
     * 删除表单规则
     */
    @GetMapping("/rulecontrol/remove_fromRule")
    @ApiOperation("删除表单规则")
    public JsonBean remove_fromRule(@ApiParam(name = "ruleid", value = "ruleid") @RequestParam(value = "ruleid", required = true) String ruleid,
                                    @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        int tiao=0;
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        try {
            tiao=this.iFormControlruleService.remove_fromRule(new BigDecimal(ruleid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "删除成功", tiao);
    }


    /**
     * 生成组织机构树
     *
     * @param nodeId
     * @param
     * @param orgId
     * @return
     */
    @GetMapping(value = "/rulecontrol/orgTree_list")
    @ApiOperation("生成组织机构树")
    public JsonBean findOrganizationByTree(@ApiParam(name = "nodeId", value = "nodeId") @RequestParam(value = "nodeId", required = false) BigDecimal nodeId,
                                           @ApiParam(name = "orgId", value = "orgId") @RequestParam(value = "orgId", required = false) BigDecimal orgId,
                                           @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        String json = "";
        if (nodeId == null) {
            nodeId = orgId;
        }
        List<Tree> list = this.iorganizationService.getNodeAll(nodeId);
        for (Tree tree : list) {
            setUrlByTree(tree, "/formControl/rulecontrol/rule_list?orgId=");
            tree.setTarget("mainFramex");
        }
        return new JsonBean(200, "success", list);


    }

    /**
     * 获取树
     */
    private void setUrlByTree(Tree tree, String url) {
        for (Tree tre : tree.getChildren()) {
            if (tre.getChildren().size() > 0) {
                setUrlByTree(tre, url);
            }
            tre.setTarget("mainFramex");
            tre.setUrl(url + tre.getId());
        }
    }

}
